<template>
  <view class="my-page">
    <!-- 顶部用户信息卡片 -->
    <view class="user-card">
      <view class="user-info">
        <up-avatar
          v-if="!userInfo.avatar"
          :text="
            userInfo.nickname ? userInfo.nickname.substring(0, 1) : 'DCS-1'
          "
          size="70"
          bgColor="#2979ff"
        ></up-avatar>
        <up-avatar
          v-else
          :src="userInfo.avatar || ''"
          size="70"
          bgColor="#2979ff"
        ></up-avatar>
        <view class="user-details">
          <text class="user-name">{{ userInfo.nickname || "未登录" }}</text>
          <text class="user-position">{{
            userInfo.position || "点击登录账号"
          }}</text>
        </view>
      </view>
    </view>

    <!-- 功能菜单 -->
    <view class="menu-section">
      <view class="section-title">常用功能</view>
      <view class="menu-grid">
        <view
          class="menu-item"
          v-for="(item, index) in commonMenus"
          :key="index"
          @click="navigateTo(item.path)"
        >
          <view class="menu-icon" :style="{ backgroundColor: item.bgColor }">
            <up-icon :name="item.icon" size="24" color="#ffffff"></up-icon>
          </view>
          <text class="menu-name">{{ item.name }}</text>
        </view>
      </view>
    </view>

    <!-- 工具列表 -->
    <view class="tools-section">
      <view class="section-title">我的工具</view>
      <view class="tools-list">
        <view
          class="tool-item"
          v-for="(item, index) in toolMenus"
          :key="index"
          @click="navigateTo(item.path)"
        >
          <view class="tool-left">
            <view class="tool-icon" :style="{ backgroundColor: item.bgColor }">
              <up-icon :name="item.icon" size="18" color="#ffffff"></up-icon>
            </view>
            <text class="tool-name">{{ item.name }}</text>
          </view>
          <up-icon name="arrow-right" size="16" color="#c0c4cc"></up-icon>
        </view>
      </view>
    </view>

    <!-- 系统设置 -->
    <view class="settings-section">
      <view class="section-title">系统设置</view>
      <view class="settings-list">
        <view
          class="setting-item"
          v-for="(item, index) in settingMenus"
          :key="index"
          @click="handleSettingClick(item)"
        >
          <view class="setting-left">
            <view
              class="setting-icon"
              :style="{ backgroundColor: item.bgColor }"
            >
              <up-icon :name="item.icon" size="18" color="#ffffff"></up-icon>
            </view>
            <text class="setting-name">{{ item.name }}</text>
          </view>
          <view class="setting-right">
            <up-switch
              v-if="item.type === 'switch'"
              v-model="item.value"
              @change="(value) => handleSwitchChange(item, value)"
            ></up-switch>
            <up-icon
              v-else
              name="arrow-right"
              size="16"
              color="#c0c4cc"
            ></up-icon>
          </view>
        </view>
      </view>
    </view>

    <!-- 退出登录按钮 -->
    <view class="logout-section" v-if="userInfo.isLogin">
      <up-button type="error" @click="handleLogout">退出登录</up-button>
    </view>
    <up-modal
      :title="confirmTitle"
      :show="confirmVisible"
      :asyncClose="true"
      showCancelButton
      closeOnClickOverlay
      @confirm="confirmCallback"
      @close="confirmVisible = false"
      @cancel="confirmVisible = false"
      ref="uModal"
    >
      <view class="slot-content">
        <text style="text-align: center">{{ confirmContent }}</text>
      </view>
    </up-modal>
    <!-- 版本信息 -->
    <view class="version-info">
      <text>当前版本 v{{ appVersion }}</text>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useUserStore } from "@/stores/user";
import { getUserInfo } from "@/api/user";
import { onLoad, onShow } from "@dcloudio/uni-app";
import {
  getToken,
  removeToken,
  getRefreshToken,
  setRefreshToken,
  isValidToken,
  logout,
} from "@/utils/auth";
import request from "@/utils/request";

const userStore = useUserStore();

const confirmVisible = ref(false);

const confirmTitle = ref("");

const confirmContent = ref("");

const confirmCallback = ref();

// 应用版本
const appVersion = ref("1.0.0");

// 用户信息
const userInfo = reactive({
  isLogin: true,
  avatar: "",
  nickname: "",
  position: "",
  email: "",
  gender: 1,
  phone: "",
});

// 菜单数据
const commonMenus = ref([
  {
    name: "数据分析",
    icon: "calendar",
    path: "/pages/index/index",
    bgColor: "#ff9900",
  },
]);

const toolMenus = ref([
  {
    name: "菜单列表",
    icon: "account",
    path: "/pages/menu/menu",
    bgColor: "#2979ff",
  },
]);

const settingMenus = ref([
  {
    name: "个人资料",
    icon: "account",
    path: "/pages/profile/profile",
    bgColor: "#2979ff",
    type: "link",
  },
  {
    name: "账号安全",
    icon: "lock",
    path: "/pages/security/security",
    bgColor: "#fa3534",
    type: "link",
  },
  {
    name: "关于我们",
    icon: "info-circle",
    path: "/pages/about/about",
    bgColor: "#8a2be2",
    type: "link",
  },
]);

// 方法
const checkLoginStatus = async () => {
  const token = getToken();
  if (token) {
    userInfo.isLogin = true;
    return;
  } else {
    if (!isValidToken(token) && getRefreshToken()) {
      const res = await request.refresh(getRefreshToken());
      if (res) {
        userInfo.isLogin = true;
        return;
      }
      userInfo.isLogin = false;
    }
    logout();
    uni.navigateTo({
      url: "/pages/login/login",
    });
  }
};

const navigateTo = (path) => {
  if (!userInfo.isLogin && path !== "/pages/login/login") {
    logout();
    uni.navigateTo({
      url: "/pages/login/login",
    });
    return;
  }

  uni.navigateTo({
    url: path,
    fail: () => {
      uni.switchTab({
        url: path,
        fail: (err) => {
          console.error("导航失败", err);
          uni.showToast({
            title: "页面不存在",
            icon: "none",
          });
        },
      });
    },
  });
};

const handleLogout = () => {
  confirmTitle.value = "退出登录";
  confirmContent.value = "确定要退出当前账号吗？";
  confirmCallback.value = () => {
    logout();
    Object.assign(userInfo, {
      isLogin: false,
      name: "未登录",
      position: "点击登录账号",
      avatar: "",
    });

    uni.showToast({
      title: "已退出登录",
      icon: "success",
    });
    confirmVisible.value = false;
  };
  confirmVisible.value = true;
};

const handleSettingClick = (item) => {
  if (item.type === "link") {
    navigateTo(item.path);
  }
};

const handleSwitchChange = (item, value) => {
  switch (item.key) {
    case "darkMode":
      console.log("深色模式:", value);
      uni.showToast({
        title: value ? "已开启深色模式" : "已关闭深色模式",
        icon: "none",
      });
      break;
    default:
      break;
  }
};

onShow(async () => {
  checkLoginStatus();
  uni.setNavigationBarTitle({
    title: "我的",
  });
  const res = await getUserInfo();
  Object.assign(userInfo, res.data);
  userInfo.position = res.data.userRoleList
    .map((item) => item.roleName)
    .join(",");
  console.log(userInfo);
  console.log(userInfo.avatar);
  const permissions = res.data.userRoleList.map((item) => item.roleName);
  userStore.setUserInfo({
    username: res.data.username,
    nickname: res.data.nickname,
    permissions: permissions,
  });
});
</script>

<style lang="scss" scoped>
.my-page {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 30px;
}

/* 用户卡片样式 */
.user-card {
  background-color: #ffffff;
  padding: 24px 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.user-details {
  margin-left: 16px;
}

.user-name {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.user-position {
  font-size: 14px;
  color: #606266;
}

.user-stats {
  display: flex;
  justify-content: space-around;
  border-top: 1px solid #ebeef5;
  padding-top: 16px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-value {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: #909399;
}

/* 部分标题样式 */
.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 16px 16px 12px;
}

/* 功能菜单样式 */
.menu-section {
  background-color: #ffffff;
  padding: 16px 0;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.menu-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  padding: 0 16px;
}

.menu-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.menu-icon {
  width: 50px;
  height: 50px;
  border-radius: 12px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 8px;
}

.menu-name {
  font-size: 12px;
  color: #606266;
}

/* 工具列表样式 */
.tools-section,
.settings-section {
  background-color: #ffffff;
  padding: 16px 0;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.tools-list,
.settings-list {
  padding: 0 16px;
}

.tool-item,
.setting-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #ebeef5;
}

.tool-item:last-child,
.setting-item:last-child {
  border-bottom: none;
}

.tool-left,
.setting-left {
  display: flex;
  align-items: center;
}

.tool-icon,
.setting-icon {
  width: 32px;
  height: 32px;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 12px;
}

.tool-name,
.setting-name {
  font-size: 14px;
  color: #303133;
}

.setting-right {
  display: flex;
  align-items: center;
}

/* 退出登录按钮 */
.logout-section {
  padding: 16px;
  margin-bottom: 16px;
}

/* 版本信息 */
.version-info {
  text-align: center;
  font-size: 12px;
  color: #909399;
  padding: 16px 0;
}

/* 登录表单 */
.login-form {
  padding: 16px;
}

/* 响应式适配 */
@media screen and (max-width: 500px) {
  .menu-grid {
    grid-template-columns: repeat(4, 1fr);
    gap: 8px;
  }

  .menu-icon {
    width: 40px;
    height: 40px;
  }

  .user-name {
    font-size: 16px;
  }

  .stat-value {
    font-size: 18px;
  }
}
</style>
